package cn.com.yx.ms.controller;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.application.web.ApiQuery;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.DevEquStore;
import cn.com.yx.ms.domain.dbmodel.DevParams;
import cn.com.yx.ms.domain.dbmodel.DevVersionRecord;
import cn.com.yx.ms.domain.dbmodel.SysRole;
import cn.com.yx.ms.domain.dev.*;
import cn.com.yx.ms.domain.program.CatalogModel;
import cn.com.yx.ms.domain.release.ReleaseModel;
import cn.com.yx.ms.persistence.DevParamsMapper;
import cn.com.yx.ms.service.IDevService;
import cn.com.yx.ms.service.IModelService;
import cn.com.yx.ms.service.IReleaseService;
import cn.com.yx.ms.service.ISysService;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.util.FileUtil;
import cn.yx.framework.util.MsgPropertyUtil;
import cn.yx.framework.view.ApiResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 设备管理
 */
@RestController
@RequestMapping(value = "dev")
@Api(value = "设备管理", description = "获取或操作设备目录、设备资源")
public class DevController {

    private static final Logger logger = LoggerFactory.getLogger(DevController.class);

    @Resource
    private MessageSource messageSource;
    @Resource
    private IDevService iDevService;
    @Resource
    private IModelService iModelService;
    @Resource
    private ISysService iSysService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IReleaseService iReleaseService;
    @Resource
    private DevParamsMapper devParamsMapper;

    // region << 设备目录 >>
    @PostMapping("catalog")
    @ApiOperation(value = "创建设备目录信息", notes = "创建设备目录信息")
    @ApiImplicitParam(paramType = "body", name = "catalogModel", dataType = "Map", required = true, value = "设备目录实体详细信息")
    public ApiResult createCatalog(@RequestBody @Validated CatalogModel catalogModel, BindingResult bindingResult) {
        return iDevService.saveDevCatalog(catalogModel);
    }

    @DeleteMapping("catalogs/{id}")
    @ApiOperation(value = "删除设备目录信息", notes = "删除设备目录信息")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "设备目录id")
    public ApiResult deleteCatalog(@PathVariable("id") String id) {
        //return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.deleteDevCatalog(id));
        return iDevService.deleteDevCatalog(id);
    }

    @PutMapping("catalog")
    @ApiOperation(value = "更新设备目录信息", notes = "更新设备目录信息")
    @ApiImplicitParam(paramType = "body", name = "catalogModel", dataType = "Map", required = true, value = "设备目录信息")
    public ApiResult updateCatalogModel(@RequestBody @Validated CatalogModel catalogModel, BindingResult bindingResult) {
        return iDevService.saveDevCatalog(catalogModel);
    }

    @PatchMapping("catalog")
    @ApiOperation(value = "设备目录信息部分更新", notes = "设备目录信息部分更新")
    @ApiImplicitParam(paramType = "body", name = "catalogModel", dataType = "Map", required = true, value = "设备目录信息")
    public ApiResult updateCatalogProperty(@RequestBody @Validated CatalogModel catalogModel, BindingResult bindingResult) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "更新成功", iDevService.updateDevCatalog(catalogModel));
    }


    @ResponseBody
    @RequestMapping(value = "catalogs", method = RequestMethod.GET)
    @ApiOperation("获取所有设备目录信息")
    public ApiResult findCatalog(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        query.getConditions().put("catalogname", request.getParameter("catalogname"));
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevCatalogs(query));
    }


    @ResponseBody
    @RequestMapping(value = "catalogs/{id}", method = GET)
    @ApiImplicitParam(paramType = "String", name = "id", dataType = "String", required = true, value = "设备目录ID")
    @ApiOperation("获取单个设备目录信息")
    public ApiResult findCatalogById(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.findDevCatalog(id));
    }

    // endregion

    // region << 设备管理 >>
    @PostMapping("equ")
    @ApiOperation(value = "创建设备信息", notes = "创建设备信息")
    @ApiImplicitParam(paramType = "body", name = "devModel", dataType = "Map", required = true, value = "设备实体详细信息")
    public ApiResult create(@RequestBody @Validated DevModel devModel, BindingResult bindingResult) {

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.saveDev(devModel));
    }

    @DeleteMapping("equs/{id}")
    @ApiOperation(value = "删除设备信息", notes = "删除设备信息")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "设备id")
    public ApiResult delete(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.deleteDev(id));
    }

    @PutMapping("equ")
    @ApiOperation(value = "更新设备信息", notes = "更新设备信息")
    @ApiImplicitParam(paramType = "body", name = "devModel", dataType = "Map", required = true, value = "设备实体详细信息")
    public ApiResult updateModel(@RequestBody @Validated DevModel devModel, BindingResult bindingResult) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.saveDev(devModel));
    }

    @PatchMapping("equ")
    @ApiOperation(value = "设备信息部分更新", notes = "设备信息部分更新")
    @ApiImplicitParam(paramType = "body", name = "devModel", dataType = "Map", required = true, value = "设备信息")
    public ApiResult updateDev(@RequestBody @Validated DevModel devModel, BindingResult bindingResult) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.saveDev(devModel));
    }

    @ResponseBody
    @RequestMapping(value = "equs", method = RequestMethod.GET)
    @ApiOperation("获取所有设备信息")
    public ApiResult findDevs(@ApiQuery ApiQueryBase query, HttpServletRequest request) {
        query.getConditions().put("devsn", request.getParameter("devsn"));
        query.getConditions().put("sname", request.getParameter("sname"));
        query.getConditions().put("catalogid", request.getParameter("catalogid"));
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.findDevs(query));
    }

    @ResponseBody
    @RequestMapping(value = "equs/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的设备信息")
    public ApiResult findDevsPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("devsn", request.getParameter("devsn"));
        query.getConditions().put("sname", request.getParameter("sname"));
        query.getConditions().put("catalogid", request.getParameter("catalogid"));
        query.getConditions().put("hardwareno", request.getParameter("hardwareno"));
        query.getConditions().put("projectstandname", request.getParameter("projectstandname"));
        query.getConditions().put("sitename", request.getParameter("sitename"));

        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevEquStore> page = (Page<DevEquStore>) iDevService.findDevs(query);
        ApiPager<DevEquStore> apiPager = new ApiPager<>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "equs/{id}", method = GET)
    @ApiImplicitParam(paramType = "String", name = "id", dataType = "String", required = true, value = "设备ID")
    @ApiOperation("获取单个设备信息")
    public ApiResult findByGgId(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.findDev(id));

    }

    // endregion

    // region << 设备继电器管理 >>

    @PostMapping("equ/channels")
    @ApiOperation(value = "创建设备继电器信息", notes = "创建设备继电器信息")
    @ApiImplicitParam(paramType = "body", name = "devChannelModel", dataType = "Map", required = true, value = "设备实体详细信息")
    public ApiResult saveChannel(@RequestBody @Validated DevChannelModel devChannelModel) {
        ApiCode apiCode = iDevService.saveDevChannel(devChannelModel);
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                apiCode == ApiCode.APP_100200,
                MsgPropertyUtil.getProperty(apiCode.msgId),
                null);
    }

    @GetMapping("equ/{devsn}/channels")
    @ApiOperation(value = "获取设备继电器信息", notes = "获取设备继电器信息")
    public ApiResult findDevChannels(@PathVariable("devsn") String devsn) {
        return iDevService.findDevChannel(devsn);
    }


    // endregion

    // region << 设备监控 >>

    @ResponseBody
    @RequestMapping(value = "monitor/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的设备监控信息")
    public ApiResult findDevCompletePage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("devsn", request.getParameter("devsn"));
        query.getConditions().put("sitename", request.getParameter("sitename"));
        query.getConditions().put("isonline", request.getParameter("isonline"));
        query.getConditions().put("isactived", request.getParameter("isactived"));
        query.getConditions().put("endcondition", request.getParameter("endcondition"));
        query.getConditions().put("catalogid", request.getParameter("catalogid"));

        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevCompleteInfoModel> page = (Page<DevCompleteInfoModel>) iDevService.findCompleteInfoModel(query);
        ApiPager<DevCompleteInfoModel> apiPager = new ApiPager<DevCompleteInfoModel>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "devposition/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的设备监控信息")
    public ApiResult findDevPositionPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("sitename", request.getParameter("sitename"));

        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevPositionModel> page = (Page<DevPositionModel>) iDevService.findDevPositionModel(query);
        ApiPager<DevPositionModel> apiPager = new ApiPager<DevPositionModel>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "devposition/all", method = RequestMethod.GET)
    @ApiOperation("获取所有设备坐标信息集合")
    public ApiResult findDevPositionAll(HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findDevPositionModel(null));
    }

    @ResponseBody
    @RequestMapping(value = "devposition/alerts", method = RequestMethod.GET)
    @ApiOperation("获取设备监告警信息")
    public ApiResult findDevPositionAlerts(@ApiQuery ApiQueryBase query, HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findDevPositionAlerts());
    }

    @ResponseBody
    @RequestMapping(value = "devpositions", method = RequestMethod.GET)
    @ApiOperation("获取所有的设备监控信息")
    public ApiResult findDevPositions(HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findDevPositionModels());
    }

    @ResponseBody
    @RequestMapping(value = "monitor/{devsn}", method = RequestMethod.GET)
    @ApiOperation("获取单个的设备监控信息")
    public ApiResult findOneDevComplete(@PathVariable("devsn") String devsn, HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findOneDevCompleteModel(devsn));
    }

    @ResponseBody
    @RequestMapping(value = "monitor/{devsn}/screen", method = RequestMethod.GET)
    @ApiOperation("获取设备截屏信息")
    public ApiResult findDevImg(@PathVariable("devsn") String devsn, HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findDevImg(devsn));
    }

    @ResponseBody
    @RequestMapping(value = "monitor/count", method = RequestMethod.GET)
    @ApiOperation("获取设备离线或在线信息")
    public ApiResult findOnlineOfflineCount() {
        return new ApiResult(AppConstant.MSG_SUCCESS, true, iDevService.findOnlineOfflineCount());
    }
    // endregion

    // region << 虚拟目录 >>

    @ResponseBody
    @RequestMapping(value = "tree/equipment", method = RequestMethod.GET)
    @ApiOperation("获取原始设备目录")
    public ApiResult findDevTreeNodes() {
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevTreeNodes());
    }

    @ResponseBody
    @RequestMapping(value = "tree/virtual", method = RequestMethod.GET)
    @ApiOperation("获取虚拟设备目录")
    public ApiResult findDevVirtualTreeNodes() {
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevVirtualTreeNodes());
    }

    @PostMapping("tree/virtual")
    @ApiOperation(value = "创建虚拟目录信息", notes = "创建虚拟目录信息")
    @ApiImplicitParam(paramType = "body", name = "devTreeModels", dataType = "Map", required = true, value = "设备目录实体详细信息")
    public ApiResult saveVirtualDev(@RequestBody List<DevTreeModel> devTreeModels) {
        return iDevService.saveVirtualDev(devTreeModels);
    }

    // endregion

    // region << 设备升级 >>

    @PostMapping("update")
    @ApiOperation(value = "上传升级包", notes = "上传升级包信息")
    public ApiResult postUpdatePackage(VersionModel versionModel, MultipartHttpServletRequest request) {
        System.out.println(request);
        ApiResult result = null;
        if (request != null) {
            try {
                String fileName = request.getFile("file").getOriginalFilename();
                FileUtil.writeFile(BaseConstant.getUploadConfig().getFilepath() + "/apk",
                        fileName,
                        request.getFile("file").getBytes());

                //保存升级包
                result = iDevService.saveDevVersionRecord(versionModel.getV(), fileName);

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                result = new ApiResult().failure();
            }
        } else {
            System.out.println("You failed to upload because the file was empty.");
            result = new ApiResult().failure();
        }

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "packages", method = RequestMethod.GET)
    @ApiOperation("获取所有升级包")
    public ApiPager<DevVersionRecord> findAllPackages(ApiQueryBase query, HttpServletRequest request) {

        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevVersionRecord> page = (Page<DevVersionRecord>) iDevService.findDevVersionRecord(query);

        ApiPager<DevVersionRecord> apiPager = new ApiPager<DevVersionRecord>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());
        return apiPager;

    }

    @ResponseBody
    @RequestMapping(value = "updatereplaylog/page", method = RequestMethod.GET)
    @ApiOperation("获取所有升级反馈记录")
    public ApiPager<UpDevUpdateLogModel> findUpDevUpdateLogs(ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("devsn", request.getParameter("devsn"));
        query.getConditions().put("sitename", request.getParameter("sitename"));
        query.getConditions().put("version", request.getParameter("version"));


        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<UpDevUpdateLogModel> page = (Page<UpDevUpdateLogModel>) iDevService.findUpDevUpdateLogs(query);

        ApiPager<UpDevUpdateLogModel> apiPager = new ApiPager<UpDevUpdateLogModel>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());
        return apiPager;

    }

    @DeleteMapping("packages/{id}")
    @ApiOperation(value = "删除设备升级信息", notes = "删除设备升级信息")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "升级包id")
    public ApiResult deleteUpdatePackage(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iDevService.deleteUpdatePackage(id));
    }
    // endregion

    // region << 设备式样同步 >>


    @PostMapping("sync/{devid}/{styleid}/{isDeleteLocalResource}")
    @ApiOperation(value = "设备式样同步", notes = "设备式样同步")
    @ApiImplicitParam(paramType = "String", name = "devid", dataType = "String", required = true, value = "设备实体详细信息")
    public ApiResult syncDevTemplate(@PathVariable("devid") String devid,
                                     @PathVariable("styleid") String styleid,
                                     @PathVariable("isDeleteLocalResource") String isDeleteLocalResource,
                                     @RequestBody @Validated List<ReleaseModel> releaseModels) throws Exception {

        if (releaseModels != null) {
            for (int i = 0; i < releaseModels.size(); i++) {
                iReleaseService.releaseProgram(releaseModels.get(i), false);
            }
        }

        ApiCode apiCode = iDevService.syncDevTemplate(devid, styleid, isDeleteLocalResource);
        return new ApiResult(AppConstant.MSG_SUCCESS, apiCode == ApiCode.APP_100200, MsgPropertyUtil.getProperty(apiCode.msgId), null);
    }


    @PostMapping("sync/defaultstyle/{devid}/{modelid}")
    @ApiOperation(value = "同步默认式样模板", notes = "同步默认式样模板")
    @ApiImplicitParam(paramType = "String", name = "devid", dataType = "String", required = true, value = "设备实体详细信息")
    public ApiResult syncDefaultStyleModel2Dev(@PathVariable("devid") String devid,
                                               @PathVariable("modelid") String modelid) throws Exception {

        // 获取默认式样
        String styleid = iSysService.findGlobalConfig().getDefaultstyleid();
        // 先更新默认式样下的模板信息
        ApiCode apiCode = iModelService.updateDefaultStyleModelId(styleid, modelid);
        // 关联默认模板区域和节目
        apiCode = iModelService.updateDefaultStyleModelProgram(styleid,modelid);

        // 同步默认式样至设备
        if(apiCode.equals(ApiCode.APP_100200)) {
            apiCode = iDevService.syncDevTemplate(devid, styleid, "1");
        }
        return new ApiResult<>(Integer.parseInt(apiCode.msgId),
                apiCode.equals(ApiCode.APP_120500) || apiCode.equals(ApiCode.APP_120501),
                MsgPropertyUtil.getProperty(apiCode.msgId));

    }

    @RequestMapping("{devid}/{styleid}/modelzip")
    public ApiResult sendGetZipCommand(@PathVariable("devid") String devid, @PathVariable("styleid") String styleid) throws Exception {
        ApiCode apiCode = iDevService.htmlZipPush(devid, styleid, "1");
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                apiCode == ApiCode.APP_100200,
                MsgPropertyUtil.getProperty(apiCode.msgId), null);
    }

    @GetMapping("updatereplayprogress")
    @ApiOperation(value = "设备升级日志", notes = "设备日志")
    @ApiImplicitParam(paramType = "String", name = "devsn", dataType = "String", required = true, value = "设备编号")
    public ApiPager<DevUpdateReplayProgress> updatereplayprogress(ApiQueryBase query, HttpServletRequest request) {
        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("devsn", request.getParameter("devsn"));
        query.getConditions().put("sitename", request.getParameter("sitename"));
        query.getConditions().put("version", request.getParameter("version"));
        //System.out.println(request.getParameter("devsn"));
        //System.out.println(iDevService.findDevUpdateReplayProgress(request.getParameter("devsn")).size());

        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevUpdateReplayProgress> page = (Page<DevUpdateReplayProgress>) iDevService.findDevUpdateReplayProgress(request.getParameter("devsn"));

        ApiPager<DevUpdateReplayProgress> apiPager = new ApiPager<DevUpdateReplayProgress>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());
        return apiPager;
    }

    @ResponseBody
    @RequestMapping(value = "styles/page", method = RequestMethod.GET)
    @ApiOperation("查找关联该设备的式样")
    public ApiResult findReleaseStyle(@ApiQuery ApiQueryBase query, HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iReleaseService.findPageResleaseStylesByDevsn(query, request));
    }

    @ResponseBody
    @RequestMapping(value = "equs/all", method = RequestMethod.GET)
    @ApiOperation("获取所有的设备信息")
    public ApiResult findAllDevEquStore(@ApiQuery ApiQueryBase query) {
        List<DevEquStore> devEquStoreList = iDevService.findDevs(query);
        CatalogModel catalogModel = new CatalogModel();
        catalogModel.setId("root");
        catalogModel.setName("设备信息目录");
        List<CatalogModel> catalogModelList = new ArrayList<CatalogModel>();
        for (DevEquStore devEquStore : devEquStoreList) {
            CatalogModel catalogModel1 = new CatalogModel();
            catalogModel1.setName(devEquStore.getEquipmentno());
            catalogModel1.setNumber("ip");
            catalogModel1.setId(devEquStore.getEquipmentguid());
            catalogModelList.add(catalogModel1);
        }
        catalogModel.setChildren(catalogModelList);
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "", catalogModel
        );
    }

    @PostMapping("equs/move")
    @ApiOperation(value = "转移设备信息", notes = "转移设备信息")
    @ApiImplicitParam(paramType = "body", name = "devTreeModels", dataType = "Map", required = true, value = "设备信息转移")
    public ApiResult saveEqusByMove(@RequestBody List<CatalogModel> catalogModels) {
        ApiCode apiCode = iDevService.saveEqusByMove(catalogModels);
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                apiCode == ApiCode.APP_500500,
                MsgPropertyUtil.getProperty(apiCode.msgId), null);
    }

    @PostMapping("saveProgramJm")
    @ApiOperation(value = "保存区域节目", notes = "保存区域节目")
    @ApiImplicitParam(paramType = "body", name = "releaseModels", dataType = "Map", required = true, value = "区域节目")
    public ApiResult saveProgramJm(@RequestBody @Validated List<ReleaseModel> releaseModels) throws Exception {
        ApiCode apiCode=ApiCode.APP_100200;
        if (releaseModels != null && releaseModels.size()>0) {
            for (int i = 0; i < releaseModels.size(); i++) {
                apiCode=iReleaseService.saveProgram(releaseModels.get(i));
                if(apiCode!=ApiCode.APP_100200){
                    break;
                }
            }
        }

        return new ApiResult(AppConstant.MSG_SUCCESS, apiCode == ApiCode.APP_100200, MsgPropertyUtil.getProperty(apiCode.msgId), null);
    }


    // endregion

    // region << 设备告警 >>

    @ResponseBody
    @RequestMapping(value = "alerts/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的设备告警信息")
    public ApiResult findAlertsPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("equipmentno", request.getParameter("equipmentno"));
        query.getConditions().put("sitename", request.getParameter("sitename"));
        query.getConditions().put("createtime", request.getParameter("createtime"));
        query.getConditions().put("sendtime", request.getParameter("sendtime"));
        String alerttype = request.getParameter("alerttype");
        if (alerttype == null || alerttype.equals("-1")) {
            alerttype = "";
        }
        query.getConditions().put("alerttype", alerttype);
        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<DevAlertInfoModel> page = (Page<DevAlertInfoModel>) iDevService.findDevAlertInfos(query);
        ApiPager<DevAlertInfoModel> apiPager = new ApiPager<DevAlertInfoModel>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "alerts/count", method = RequestMethod.GET)
    @ApiOperation("获取带设备告警数量")
    public ApiResult findAlertCount(@ApiQuery ApiQueryBase query, HttpServletRequest request) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iDevService.findDevAlertCount());
    }

    @PostMapping("revokeAlerts")
    @ApiOperation(value = "撤销告警")
    @ApiImplicitParam(paramType = "body", name = "devAlertInfoModel", dataType = "Map", required = true, value = "撤销告警")
    public ApiResult revokeAlerts(@RequestBody List<DevAlertInfoModel> list) {
        ApiCode apiCode = iDevService.revokeAlerts(list);
        return new ApiResult<>(AppConstant.MSG_SUCCESS, apiCode == ApiCode.APP_600500, MsgPropertyUtil.getProperty(apiCode.msgId), null);
    }

    // endregion

    // region << 式样下的设备 >>

    /**
     * 获取式样下设备（显示已关联其他式样的名称）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "tree/equipmentwithstyle", method = RequestMethod.GET)
    @ApiOperation("获取原始设备目录带式样名")
    public ApiResult findDevTreeNodesWithStyle() {
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevTreeNodesWithStyleName());
    }

    @ResponseBody
    @RequestMapping(value = "tree/virtualwithstyle", method = RequestMethod.GET)
    @ApiOperation("获取虚拟设备目录带式样名")
    public ApiResult findDevVirtualTreeNodesWithStyle() {
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevVirtualTreeNodesWithStyle());
    }
    // endregion

    @ResponseBody
    @RequestMapping(value = "tree/virtualwithstyle/{styleid}", method = RequestMethod.GET)
    @ApiOperation("获取虚拟设备目录带式样名")
    public ApiResult findDevVirtualTreeNodesWithStyle(@PathVariable("styleid") String styleid) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iDevService.findDevVirtualTreeNodesWithStyle(styleid));
    }

    @GetMapping("params/{devsn}")
    @ApiOperation("设备参数")
    public ApiResult findDevParams(@PathVariable("devsn") String devsn) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", devParamsMapper.selectByEquipmentno(devsn));
    }

}